/////////////////////////////////////////////////////////////////////////
//
// GAM203
// Shader wrapper class
// Shader.cpp
// 
// Scott Taylor
// Qantm College
//
//////////////////////////////////////////////////////////////////////////

#include "Shader.h"

#include <d3dx9.h>

Shader::Shader(const char* a_pName)
  : m_pEffect(NULL)
{
  if (a_pName)
  {
    // Take a copy of the name passed in
    strcpy_s(m_name, sizeof(m_name), a_pName);
  }
  else
  {
    // Caller is dodgy! But NULL-terminate our name so we don't crash...
    m_name[0] = 0;
  }
}

Shader::~Shader()
{
  if (m_pEffect)
  {
    m_pEffect->Release();
    m_pEffect = NULL;
  }
}

//
// Loads this shader
// Returns true if successful
//
bool Shader::Load(IDirect3DDevice9* a_pDevice, const char* a_pEffectFilename)
{
  if (!a_pDevice || m_pEffect)
  {
    // No device, or we already have an effect loaded
    return false;
  }

  if (!a_pEffectFilename || !a_pEffectFilename[0])
  {
    // No effect filename was given
    return false;
  }

  // Buffer for error output (used if compile error occurs in shader)
  ID3DXBuffer* pErrorBuf = NULL;

  // Attempt to compile shader
  HRESULT result = D3DXCreateEffectFromFile(a_pDevice, a_pEffectFilename, NULL, NULL, 0, NULL,
    &m_pEffect, &pErrorBuf);

  if (FAILED(result))
  {
    // Shader failed to load
    if (pErrorBuf && pErrorBuf->GetBufferPointer())
    {
      // We have compile error info; spit it out to debug log
      OutputDebugString((const char*)pErrorBuf->GetBufferPointer());
    }
    else
    {
      // No compile error info; was probably some error that happened before compilation
      OutputDebugString("Failed to create shader; no compile error info");
    }
    return false;
  }

  // Shader successfully loaded!
  return true;
}

